<template>
  <div class="donut-chart-container">
    <div ref="chartRef" class="chart-wrapper"></div>
    <div class="chart-info" v-if="chartData.length > 0">
      <div class="gender-stats">
        <div class="gender-item male">
          <div class="flex" style="align-items: center;">
            <span class="gender-dot"></span>
            <span class="gender-name">{{ chartData[0]?.name || '男' }}</span>
          </div>
         
          <div>
            <span class="gender-count">{{ chartData[0]?.value || 0 }}人</span>
            <span class="gender-percent">{{ getPercent(chartData[0]?.value) }}%</span>
          </div>
         
        </div>
        <div class="gender-item female">
          <div class="flex"  style="align-items: center;">
            <span class="gender-dot"></span>
            <span class="gender-name">{{ chartData[1]?.name || '女' }}</span>
          </div>
         
          <div>
            <span class="gender-count">{{ chartData[1]?.value || 0 }}人</span>
            <span class="gender-percent">{{ getPercent(chartData[1]?.value) }}%</span>
          </div>
         
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "DonutChart",
  props: {
    // 图表数据，格式: [{name: '类别1', value: 100}, ...]
    chartData: {
      type: Array,
      default: () => [],
    },
    // 图表标题
    title: {
      type: String,
      default: "",
    },
    // 环形图内径与外径比例
    radiusRatio: {
      type: Number,
      default: 0.5,
      validator: (value) => value > 0 && value < 1,
    },
    // 中间文本配置
    centerText: {
      type: Object,
      default: () => ({
        text: "总共\n4106人",
      }),
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  computed: {
    // 计算总数值
    totalValue() {
      return this.chartData.reduce((sum, item) => sum + item.value, 0);
    },
    // 提取标签和数值
    labels() {
      return this.chartData.map((item) => item.name);
    },
    values() {
      return this.chartData.map((item) => item.value);
    },
    // 动态计算环形图中间显示的文本
    centerTitle() {
      if (this.centerText && this.centerText.text) {
        return this.centerText.text;
      }
      return `共${this.chartData.length}个\n云店`;
    },
    // 动态计算饼图颜色
    chartColors() {
      const defaultColors = ["#348CF8", "#FF5F74", "#F7B500", "#5AD8A6"];
      // 如果chartData中有color属性，则使用数据中的颜色
      const hasCustomColors = this.chartData.some(item => item.color);
      if (hasCustomColors) {
        return this.chartData.map(item => item.color || defaultColors[0]);
      }
      return defaultColors;
    },
    // 计算饼图半径
    chartRadius() {
      const outerRadius = 40 - this.radiusRatio * 10; // 根据比例调整外径
      return [`${this.radiusRatio * 100}%`, `${outerRadius}%`];
    }
  },
  mounted() {
    // 初始化图表
    this.initChart();
    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例，释放资源
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {
    // 监听图表数据变化，重新渲染图表
    chartData: {
      handler(newData) {
        if (this.chart && newData && newData.length > 0) {
          this.updateChart();
        }
      },
      deep: true
    },
    // 监听标题变化，更新图表标题
    title: {
      handler(newTitle) {
        if (this.chart) {
          this.chart.setOption({
            title: {
              text: newTitle
            }
          });
        }
      }
    },
    // 监听比例变化，更新图表半径
    radiusRatio: {
      handler() {
        if (this.chart) {
          this.updateChart();
        }
      }
    }
  },
  methods: {
     // 计算百分比
     getPercent(value) {
      if (!value || this.totalValue === 0) return 0;
      return Math.round((value / this.totalValue) * 100);
    },
    initChart() {
      if (!this.$refs.chartRef) return;
      
      // 初始化图表实例
      this.chart = echarts.init(this.$refs.chartRef);
      this.updateChart();
    },
    
    // 更新图表配置
    updateChart() {
      if (!this.chart || !this.chartData || this.chartData.length === 0) return;
      
      // 设置图表配置项
      const option = {
        title: {
          text: this.title || "",
          left: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
            color: "#333"
          }
        },
        color: this.chartColors,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "left",
          show: false,
          data: this.labels
        },
        graphic: [
          {
            type: "text",
            left: "center",
            top: "26%",
            style: {
              text: this.centerTitle,
              textAlign: "center",
              fill: "#005947",
              fontSize: "15",
              fontWeight: "bold",
              lineHeight: 22
            },
          },
        ],
        series: [
          {
            name: this.title || "用户性别占比",
            type: "pie",
            radius: this.chartRadius,
            center: ["50%", "30%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 0,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: "outside",
              color: "#000",
              fontSize: 13,
              alignTo: "labelLine",
              formatter: "{b}\n({d}%)"
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            labelLine: {
              show: true
            },
            data: this.chartData
          },
        ],
        // 动画配置
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      };

      // 设置配置项到图表
      this.chart.setOption(option, true);
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    
    // 提供外部更新数据的方法
    updateData(newData) {
      // 触发事件，让父组件更新数据，而不是直接修改props
      this.$emit('update-data', newData);
    }
  },
};
</script>

<style scoped>
.donut-chart-container {
  position: relative;
  width: 100%;
  min-width: 300px;
  max-width: 600px;
  margin: 0 auto;
}

.chart-wrapper {
  width: 100%;
  height: 250px;
}

.chart-info {
  text-align: center;
  margin-top: -90px;
}

.total {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.chart-info {
  text-align: center;
  margin-top: -90px;
}

.gender-stats {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px; /* 男女生之间的间距 */
}

.gender-item {
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.gender-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-bottom: 5px;
  margin-right: 5px;
}

/* 男生的点使用蓝色 */
.gender-item.male .gender-dot {
  background-color: #348CF8;
}

/* 女生的点使用红色 */
.gender-item.female .gender-dot {
  background-color: #FF5F74;
}

.gender-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
  font-weight: bold;
}

.gender-count,
.gender-percent {
  font-size: 13px;
  color: #666;
  font-weight: bold;
}

.gender-count {
  margin-right: 8px;
}

/* 确保在小屏幕上也能良好显示 */
@media (max-width: 480px) {
  .gender-stats {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
